<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="方案编号" prop="programCode">
        <el-input
            v-model="queryParams.programCode"
            placeholder="请输入方案编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="方案名称" prop="name" >
        <el-input
            v-model="queryParams.name"
            placeholder="请输入方案名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属学院" prop="collegeId">
        <el-select
            v-model="queryParams.collegeId"
            placeholder="请输入学院名称/代码"
            clearable
            filterable
            remote
            :remote-method="filterColleges"
            :loading="collegeLoading"
            style="width: 200px;"
            @change="handleQuery"
        >
          <el-option
              v-for="college in filteredColleges"
              :key="college.collegeId"
              :label="`${college.collegeName} (${college.collegeCode})`"
              :value="college.collegeId"
          >
            <span style="float: left">{{ college.collegeName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ college.collegeCode }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="专业" prop="majorId">
        <el-input
            v-model="queryParams.majorId"
            placeholder="请输入专业"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择年级" clearable style="width: 150px;">
          <el-option
              v-for="dict in grade"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="培养方案类型" prop="cultureProgramType">
        <el-select v-model="queryParams.cultureProgramType" placeholder="请选择培养方案类型" clearable style="width: 150px;">
          <el-option
              v-for="dict in culture_program_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable style="width: 150px;">
          <el-option
              v-for="dict in audit_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAddByPage"
            v-hasPermi="['trainingManagement:trainingManagement:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            icon="CopyDocument"
            @click="handleAddFromTemplate"
            :disabled="!selectedRows.length"
            v-hasPermi="['trainingManagement:trainingManagement:add']"
        >从模板新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['trainingManagement:trainingManagement:edit']"
            v-if="selectedItemsHaveStatus3"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['trainingManagement:trainingManagement:remove']"
            v-if="selectedItemsHaveStatus3"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['trainingManagement:trainingManagement:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="trainingManagementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="方案编号" align="center" prop="programCode" />
      <el-table-column label="方案名称" align="center" prop="name" />
      <el-table-column label="所属学院" align="center">
        <template #default="scope">
          <span>{{ getCollegeName(scope.row.collegeId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总学分要求" align="center" prop="totalCredits" />
<!--      <el-table-column label="专业" align="center">-->
<!--        <template #default="scope">-->
<!--          <span>{{getMajorInfo(scope.row.majorId)}}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="学科" align="center">
        <template #default="scope">
          <span v-html="subjectCache[scope.row.id] || '加载中...'"></span>
        </template>
      </el-table-column>
      <el-table-column label="研究方向" align="center">
        <template #default="scope">
          <span>{{ researchDirectionCache[scope.row.id] || '加载中...' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="英文名称" align="center" prop="englishName" />
<!--      <el-table-column label="学位课学分" align="center" prop="degreeCourseCredit" />-->
<!--      <el-table-column label="必修环节学分" align="center" prop="requiredCourseCredits" />-->
      <el-table-column label="年级" align="center" prop="grade">
        <template #default="scope">
          <dict-tag :options="grade" :value="scope.row.grade"/>
        </template>
      </el-table-column>
      <el-table-column label="培养方案类型" align="center" prop="cultureProgramType" width="120">
        <template #default="scope">
          <dict-tag :options="culture_program_type" :value="scope.row.cultureProgramType"/>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="status" width="100">
        <template #default="scope">
          <dict-tag :options="audit_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="getTrainingManagementCourseList(scope.row.id)" v-hasPermi="['trainingManagement:programPourses:query']">查看课程信息</el-button>
          <el-button link type="primary"
                     @click="navigateToDesignatedProgram(scope.row)"
                     v-hasPermi="['trainingManagement:trainingManagement:edit']"
                     v-if="scope.row.status === 1">
            培养方案指定
          </el-button>
          <el-button link type="primary"
                     @click="handleUpdates(scope.row, true)"
                     v-if="scope.row.status === 2 && isAuthorizedToReview">
            审核培养方案
          </el-button>
          <!-- 仅当状态为3时显示修改按钮 -->
          <el-button link type="primary"
                     @click="handleUpdates(scope.row)"
                     v-hasPermi="['trainingManagement:trainingManagement:edit']"
                     v-if="scope.row.status === 3">
            修改
          </el-button>
          <!-- 仅当状态为3时显示删除按钮 -->
          <el-button link type="primary"
                     @click="handleDelete(scope.row)"
                     v-hasPermi="['trainingManagement:trainingManagement:remove']"
                     v-if="scope.row.status === 3">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 查看课程详细信息对话框 -->
    <el-dialog v-model="openDetail" width="1500px" append-to-body class="training-detail-dialog">
      <template #header>
        <div style="width:100%; text-align:center; font-size:20px; font-weight:bold;">
          课程详细信息
          <span style="float:right; font-size:16px; font-weight:normal; color:#606266;">
            培养方案名称：<strong>{{ currentTrainingProgramName }}</strong>
          </span>
        </div>
      </template>
      <el-table
          :data="programPoursesList"
          border
          :span-method="objectSpanMethod"
      >
        <el-table-column label="课程性质" align="center">
          <template #default="scope">
            <dict-tag :options="characteristics_of_the_course" :value="scope.row.courseCharacter" />
          </template>
        </el-table-column>
        <el-table-column label="课程编号" align="center">
          <template #default="scope">
            {{ getCourseCode(scope.row.courseId) }}
          </template>
        </el-table-column>
        <el-table-column label="课程名称" align="center">
          <template #default="scope">
            {{ getCourseName(scope.row.courseId) }}
          </template>
        </el-table-column>
        <el-table-column label="总学时" align="center" prop="totalHours" />
        <el-table-column label="学分" align="center" prop="credits" />
        <el-table-column label="授课方式" align="center" prop="teachingMethod">
          <template #default="scope">
            <dict-tag :options="teaching_method" :value="scope.row.teachingMethod"/>
          </template>
        </el-table-column>
        <el-table-column label="考试方式" align="center" prop="examMethod">
          <template #default="scope">
            <dict-tag :options="method_examination" :value="scope.row.examMethod"/>
          </template>
        </el-table-column>
        <el-table-column label="开课学期" align="center" prop="semester">
          <template #default="scope">
            <dict-tag :options="semester" :value="scope.row.semester" />
          </template>
        </el-table-column>
        <el-table-column label="是否必修" align="center" prop="isRequired">
          <template #default="scope">
            <dict-tag :options="compulsory" :value="scope.row.isRequired"/>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="openDetail = false">关闭</el-button>
      </template>
    </el-dialog>


    <!--添加或修改培养方案管理对话框-->
    <el-dialog :title="title" v-model="open" width="1500px" append-to-body>
      <div class="tab-buttons">
        <el-button
            :type="activeTab === 'program' ? 'primary' : 'default'"
            @click="activeTab = 'program'"
            class="tab-btn"
        >
          培养方案信息管理
        </el-button>
        <el-button
            :type="activeTab === 'course' ? 'primary' : 'default'"
            @click="activeTab = 'course'"
            class="tab-btn"
        >
          课程管理
        </el-button>
      </div>

      <el-form ref="trainingManagementRef" :model="form" :rules="crules" label-width="100px">
        <div v-if="activeTab === 'program'">
          <el-row :gutter="20" class="form-grid">
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item label="方案编号" prop="programCode">
                <el-input v-model="form.programCode" placeholder="请输入方案编号" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item label="方案名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入方案名称" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item label="所属学院" prop="collegeId">
                <el-select
                    v-model="form.collegeCode"
                    placeholder="请输入学院名称/代码"
                    clearable
                    filterable
                    remote
                    :remote-method="filterColleges"
                    :loading="collegeLoading"
                    style="width: 100%;"
                    @change="handleCollegeChange"
                >
                  <el-option
                      v-for="college in filteredColleges"
                      :key="college.collegeId"
                      :label="`${college.collegeName} (${college.collegeCode})`"
                      :value="college.collegeCode"
                  >
                    <span style="float: left">{{ college.collegeName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ college.collegeCode }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item label="专业" prop="majorId">
                <el-select
                    v-model="form.majorId"
                    placeholder="请选择专业"
                    style="width: 100%"
                    :disabled="!form.collegeCode"
                >
                  <el-option
                      v-for="m in MajorList"
                      :key="m.id"
                      :label="m.majorName"
                      :value="m.id.toString()"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="年级" prop="grade">
                <el-select v-model="form.grade" placeholder="请选择年级" style="width: 100%">
                  <el-option v-for="dict in grade" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="培养方案类型" prop="cultureProgramType">
                <el-select v-model="form.cultureProgramType" placeholder="请选择培养方案类型" style="width: 100%">
                  <el-option v-for="dict in culture_program_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item label="总学分要求" prop="totalCredits">
                <el-input v-model="form.totalCredits" placeholder="请输入总学分要求" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item label="学位课学分" prop="degreeCourseCredit">
                <el-input v-model="form.degreeCourseCredit" placeholder="请输入学位课学分" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item label="必修环节学分" prop="requiredCourseCredits">
                <el-input v-model="form.requiredCourseCredits" placeholder="请输入必修环节学分" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <el-form-item label="英文名称" prop="englishName">
                <el-input v-model="form.englishName" placeholder="请输入英文名称" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="6">
              <el-form-item label="审核状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择审核状态" style="width: 100%">
                  <el-option v-for="dict in audit_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="6">
              <el-form-item label="限制条件" prop="limitingCondition">
                <el-input v-model="form.limitingCondition" placeholder="请输入限制条件" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="6">
              <el-form-item label="附件上传" prop="attachmentUploadPath">
                <file-upload v-model="form.attachmentUploadPath"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div v-if="activeTab === 'course'">
          <el-row :gutter="20" class="form-grid">
            <el-col :xs="24" :sm="24" :md="24" :lg="24">
              <el-form-item label="课程管理">
                <div class="search-container">
                  <div class="search-course-group">
                    <el-input
                        v-model="form.courseSearch"
                        placeholder="输入课程名称/编号搜索（支持模糊匹配）"
                        @keyup.enter="searchCourses"
                        style="width: 400px"
                    />
                    <el-button
                        type="primary"
                        @click="searchCourses"
                        :loading="searchLoading"
                        class="ml-8"
                    >
                      搜索课程
                    </el-button>
                  </div>
                  <div v-if="searchCourseList.length > 0" class="search-results mt-8">
                    <div
                        v-for="course in searchCourseList"
                        :key="course.id"
                        class="result-item"
                        @click="selectCourse(course)"
                    >
                      <span>{{ course.courseName }}</span>
                      <div class="meta">
                        编号：{{ course.courseCode }} | 学分：{{ course.credits }}
                      </div>
                    </div>
                  </div>
                </div>
                <div class="selected-courses mt-16">
                  <el-table
                      :data="form.courses"
                      border
                      max-height="450"
                      style="width: 100%; table-layout: fixed;"
                      stripe>
                    <el-table-column label="课程名称" prop="courseName" width="180" />
                    <el-table-column label="开课学院" prop="collegeId" width="90" />
                    <el-table-column label="学分" width="120">
                      <template #default="scope">
                        <el-input-number
                            v-model="scope.row.credits"
                            :min="0"
                            :max="100"
                            size="small"
                            controls-position="right"
                            @change="updateTotalCredits"
                            style="width: 100%; padding: 0 8px;"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="总学时" width="120">
                      <template #default="scope">
                        <el-input-number
                            v-model="scope.row.totalHours"
                            :min="0"
                            :max="1000"
                            size="small"
                            controls-position="right"
                            style="width: 100%; padding: 0 8px;"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="年级" align="center" prop="grade">
                      <template #default="scope">
                        <dict-tag :options="grade" :value="form.grade"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="开课学期" width="120">
                      <template #default="scope">
                        <el-select
                            v-model="scope.row.courseSemester"
                            placeholder="请选择学期"
                            size="small"
                            style="width: 100%"
                        >
                          <el-option
                              v-for="dict in semester"
                              :key="dict.value"
                              :label="dict.label"
                              :value="parseInt(dict.value)"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="授课方式" width="120">
                      <template #default="scope">
                        <el-select v-model="scope.row.teachingMethod" placeholder="请选择授课方式" size="small">
                          <el-option
                              v-for="dict in teaching_method"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="考试方式" width="120">
                      <template #default="scope">
                        <el-select v-model="scope.row.examMethod" placeholder="请选择考试方式" size="small">
                          <el-option
                              v-for="dict in method_examination"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="是否必修" width="100">
                      <template #default="scope">
                        <el-switch
                            v-model="scope.row.isRequired"
                            active-text="是"
                            inactive-text="否"
                            active-value="1"
                            inactive-value="0"
                            size="small"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="课程性质" width="120">
                      <template #default="scope">
                        <el-select
                            v-model="scope.row.courseNature"
                            placeholder="请选择课程性质"
                            size="small"
                        >
                          <el-option
                              v-for="dict in characteristics_of_the_course"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                      <template #default="scope">
                        <el-button
                            type="danger"
                            icon="Delete"
                            size="small"
                            @click="removeCourse(scope.$index)"
                        >删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div
                    v-if="form.courses.length === 0"
                    class="empty-tips mt-8"
                    style="color: #909399;"
                >
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 培养方案指定对话框 -->
    <el-dialog
        :title="'培养方案指定'"
        v-model="showTrainingProgramDialog"
        width="80%"
        @close="cancel"
        class="training-assign-dialog"
    >
      <el-form :model="trainingProgramForm" label-width="100px" class="grid-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="方案编号">
              <el-input v-model="trainingProgramForm.programCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="方案名称">
              <el-input v-model="trainingProgramForm.name" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="所属学院">
              <el-input
                  :value="collegeDisplayName"
                  disabled
                  style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="总学分要求">
              <el-input v-model="trainingProgramForm.totalCredits" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="专业">
              <el-input v-model="trainingProgramForm.majorName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="英文名称">
              <el-input v-model="trainingProgramForm.englishName" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="学位课学分">
              <el-input v-model="trainingProgramForm.degreeCourseCredit" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="必修环节学分">
              <el-input v-model="trainingProgramForm.requiredCourseCredits" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="年级">
              <dict-tag :options="grade" :value="trainingProgramForm.grade"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="培养方案类型">
              <dict-tag :options="culture_program_type" :value="trainingProgramForm.cultureProgramType"    />
            </el-form-item>
          </el-col>
        </el-row>
        <h1>专业信息</h1>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="专业代码">
              <el-input v-model="majorForm.majorCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="专业名称">
              <el-input v-model="majorForm.majorName" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4">
            <el-form-item label="培养类型">
              <el-input v-model="majorForm.majorCultureCategory" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <h1>该年级专业对应的学生信息</h1>
        <el-table v-loading="loading" :data="studentMangerList" @selection-change="handleStudentSelectionChange">
          <el-table-column type="selection" width="60" align="center" :selectable="isStudentSelectable"/>
          <el-table-column label="学号" align="center" prop="studentId" />
          <el-table-column label="姓名" align="center" prop="studentName" />
          <el-table-column label="所属学院" align="center">
            <template #default="scope">
              <span>{{ getCollegeName(scope.row.studentYx) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="培养方案名称" align="center">
            <template #default="scope">
              {{ getTrainingProgramName(scope.row.trainingProgramId) }}
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="assignTrainingProgram" :disabled="selectedStudents.length === 0 || assigning">
            确认指定该培养方案 ({{ selectedStudents.length }})
          </el-button>
        <el-button @click="showTrainingProgramDialog = false">关 闭</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="TrainingManagement">
import useUserStore from '@/store/modules/user';
import { listTrainingManagement, getTrainingManagement, delTrainingManagement, addTrainingManagement, updateTrainingManagement, addTrainingProgramWithCourses, updateProgramWithCourses } from "@/api/trainingManagement/trainingManagement";
import { listProgramPourses, addProgramPourses, updateProgramPourses, delProgramPourses } from "@/api/trainingManagement/programPourses";
import { selectTrainingProgramListByCollegeIds } from "@/api/student/allList";
import { loadAllParams } from "@/api/page";
import { getProgramPoursesByTrainingId } from "@/api/trainingManagement/programPourses";
import { listMajor, getMajor, getMajorByCollegeId } from "@/api/major/major.js";
import { listCourse } from "@/api/course/course";
import axios from 'axios';
import { getCurrentInstance, ref, reactive, toRefs, computed, onMounted, watch } from 'vue';
import { batchAddProgramCourses } from "@/api/trainingManagement/programPourses";
import { listCollege } from "@/api/college/college";
import { debounce } from 'lodash';
import { listByStudentZyAndNj, assignTrainingToStudents } from "@/api/student/studentManger";
import router from '@/router'; // 补充路由导入
import { getSubjectIdListByProgramId } from "@/api/college/researchDirection";
const { proxy } = getCurrentInstance();
const { characteristics_of_the_course, type_of_course, semester, audit_status, course_status, status, culture_program_type, grade, teaching_method, method_examination, course_nature, compulsory } = proxy.useDict('characteristics_of_the_course', 'type_of_course', 'semester', 'audit_status', 'course_status', 'status', 'culture_program_type', 'grade', 'teaching_method', 'method_examination', 'course_nature', 'compulsory');
const openDetail = ref(false);
const trainingManagementList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeTab = ref('program');
const collegeList = ref([]);
const filteredColleges = ref([]);
const collegeLoading = ref(false);
const searchCourseList = ref([]);
const yxList = ref([]);
const zyZlist = ref([]);
const xuezhi = ref([]);
const searchLoading = ref(false);
const selectedStudents = ref([]);
const assigning = ref(false);
const currentTrainingProgramName = ref(''); // 补充缺失的变量声明
const courseList = ref([]); // 课程列表
const subjectList = ref([]);//学科信息列表
const subjectCache = ref({});
const researchDirectionCache = ref({});
// 补充专业表单声明
const majorForm = reactive({
  majorCode: '',
  majorName: '',
  majorCultureCategory: ''
});

const data = reactive({
  form: {
    courses: [],
    courseSearch: '',
    collegeCode: null, // 补充学院代码字段
    id: null,
    programCode: null,
    name: null,
    studentType: null,
    collegeId: null,
    totalCredits: null,
    majorId: null,
    englishName: null,
    degreeCourseCredit: null,
    requiredCourseCredits: null,
    grade: null,
    cultureProgramType: null,
    majorCultureCategory: null,
    majorCode: null,
    majorName: null,
    attachmentUploadPath: null,
    limitingCondition: null,
    status: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    programCode: null,
    name: null,
    studentType: null,
    collegeId: null,
    totalCredits: null,
    majorId: null,
    englishName: null,
    degreeCourseCredit: null,
    requiredCourseCredits: null,
    grade: null,
    cultureProgramType: null,
    limitingCondition: null,
    status: null,
    fromTemplateId: null
  },
  rules: {
    name: [
      { required: true, message: "方案名称不能为空", trigger: "blur" }
    ],
    collegeId: [
      { required: true, message: "所属学院id不能为空", trigger: "blur" }
    ],
    totalCredits: [
      { required: true, message: "总学分要求不能为空", trigger: "blur" }
    ],
  }
});

const showTrainingProgramDialog = ref(false);
const trainingProgramForm = reactive({
  programCode: '',
  name: '',
  collegeId: '',
  totalCredits: '',
  majorId: '',
  majorName: '', // 补充专业名称字段
  englishName: '',
  degreeCourseCredit: '',
  requiredCourseCredits: '',
  grade: '',
  cultureProgramType: '', // 修正拼写错误
  status: '',
  attachmentUploadPath: '',
  limitingCondition: ''
});
const studentMangerList = ref([]);
const selectedRows = ref([]); // 用于存储选中的行数据

const { queryParams, form, rules } = toRefs(data);

// 计算属性：判断选中的项是否都有状态3
const selectedItemsHaveStatus3 = computed(() => {
  return selectedRows.value.every(row => row.status === 3);
});

function getList() {
  loading.value = true;
//  listTrainingManagement(queryParams.value).then(response => {
  selectTrainingProgramListByCollegeIds().then(response => {
    trainingManagementList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 获取学科信息
const getSubjectInfo = async (programId) => {
  if (!programId) {
    subjectCache.value[programId] = '-';
    return '-';
  }

  // 检查缓存
  if (subjectCache.value[programId] !== undefined) {
    return subjectCache.value[programId];
  }

  try {
    // 先设置加载状态
    subjectCache.value[programId] = '加载中...';

    // 调用接口获取学科信息
    const response = await getSubjectIdListByProgramId(programId);
    const subjectList = response.data || [];

    // 处理接口返回的数据 - 一二级学科换行显示
    let subjectText = '';
    if (subjectList.length > 0) {
      subjectText = subjectList.map(item => {
        // 基础信息：一级学科
        let baseInfo = `${item.firstSubjectName}(${item.firstSubjectCode})`;

        // 如果有二级学科，添加二级学科信息（换行显示）
        if (item.secondSubjectName && item.secondSubjectCode) {
          baseInfo += `<br>${item.secondSubjectName}(${item.secondSubjectCode})`;
        }

        return baseInfo;
      }).join('；');
    } else {
      subjectText = '无学科信息';
    }

    // 缓存结果
    subjectCache.value[programId] = subjectText;
    return subjectText;
  } catch (error) {
    console.error(`获取培养方案 ${programId} 的学科信息失败:`, error);
    subjectCache.value[programId] = '获取失败';
    return '获取失败';
  }
};

// 新增研究方向获取函数
const getResearchDirections = async (programId) => {
  if (!programId) {
    researchDirectionCache.value[programId] = '-';
    return '-';
  }

  // 检查缓存
  if (researchDirectionCache.value[programId] !== undefined) {
    return researchDirectionCache.value[programId];
  }

  try {
    // 先设置加载状态
    researchDirectionCache.value[programId] = '加载中...';

    // 调用接口获取学科信息
    const response = await getSubjectIdListByProgramId(programId);
    const subjectList = response.data || [];

    // 处理接口返回的数据 - 只提取研究方向
    let directionsText = '';
    const allDirections = [];

    if (subjectList.length > 0) {
      subjectList.forEach(item => {
        // 确保directionReturnVoList存在且是数组
        if (Array.isArray(item.directionReturnVoList) && item.directionReturnVoList.length > 0) {
          const directions = item.directionReturnVoList.map(dir => dir.name || dir.directionName);
          allDirections.push(...directions);
        }
      });

      if (allDirections.length > 0) {
        directionsText = allDirections.join('、');
      } else {
        directionsText = '无研究方向';
      }
    } else {
      directionsText = '无研究方向';
    }

    // 缓存结果
    researchDirectionCache.value[programId] = directionsText;
    return directionsText;
  } catch (error) {
    console.error(`获取培养方案 ${programId} 的研究方向失败:`, error);
    researchDirectionCache.value[programId] = '获取失败';
    return '获取失败';
  }
};
// 在这里插入watch代码
// 当列表数据加载完成后预加载学科信息
watch(trainingManagementList, async (newList) => {
  if (newList && newList.length > 0) {
    // 批量预加载学科信息和研究方向
    for (const item of newList) {
      if (item.id) {
        if (!subjectCache.value[item.id]) {
          await getSubjectInfo(item.id);
        }
        if (!researchDirectionCache.value[item.id]) {
          await getResearchDirections(item.id);
        }
      }
    }
  }
});
const totalCredits = computed(() =>
    data.form.courses.reduce((sum, course) => sum + (course.credits || 0), 0)
);
function selectCourse(course) {
  // 检查是否已添加该课程
  const exists = form.value.courses.some(c => c.courseId === course.id);
  if (exists) {
    proxy.$modal.msgWarning("该课程已添加");
    return;
  }
  // 添加课程并更新总学分
  form.value.courses.push({
    courseId: course.id,
    courseName: course.courseName,
    courseCode: course.courseCode,
    credits: course.credits || 0,
    totalHours: course.totalHours || 0
  });
  updateTotalCredits(); // 重新计算总学分
  console.log("已添加课程：", course.courseName, "，当前总学分：", form.value.totalCredits);
}
const userStore = useUserStore();
onMounted(() => {
  const username = userStore.name;
  console.log('用户名（userName）：', username);
  console.log('用户信息（userStore）：', userStore);
  console.log('用户信息（userStore.roles）：', userStore.roles);
  watch(() => data.form.id, async (id) => {
    if (id) {
      data.form.courses = await getCourseByTrainingId(id);
    }
  });
  fetchCollegeList();
  getList();
  getCourseList();
  getMajorList();
  getProgramPoursesList();
  getAllTrainingPrograms();
  listMajor(loadAllParams).then(response => {
    MajorList.value = response.rows || response;
  });
});

const searchCourses = async () => {
  if (!form.value.courseSearch?.trim()) {
    proxy.$modal.msgWarning("请输入课程名称");
    return;
  }
  searchLoading.value = true;
  try {
    const res = await listCourse({
      courseName: form.value.courseSearch,
      pageSize: 100
    });
    searchCourseList.value = res.rows.map(course => ({
      ...course,
      highlightName: highlightCourseName(course)
    }));
  } catch (e) {
    proxy.$modal.msgError('课程搜索失败');
  } finally {
    searchLoading.value = false;
  }
};

const highlightCourseName = (course) => {
  const searchText = form.value.courseSearch;
  return course.courseName.replace(
      new RegExp(`(${searchText})`, 'gi'),
      '<span class="highlight">$1</span>'
  );
};

function cancel() {
  open.value = false;
  reset();
  activeTab.value = 'program';
}

function removeCourse(index) {
  proxy.$modal.confirm('是否确认删除此课程明细？').then(() => {
    form.value.courses.splice(index, 1);
    updateTotalCredits();
  });
}

const collegeDisplayName = computed(() => {
  return getCollegeName(trainingProgramForm.collegeId);
});

const updateTotalCredits = () => {
  form.value.totalCredits = form.value.courses.reduce(
      (sum, course) => sum + (Number(course.credits) || 0),
      0
  );
};

const crules = reactive({
  name: [
    { required: true, message: "方案名称不能为空", trigger: "blur" }
  ],
  collegeId: [
    { required: true, message: "所属学院id不能为空", trigger: "blur" }
  ],
  totalCredits: [
    { required: true, message: "总学分要求不能为空", trigger: "blur" }
  ],
  courses: [
    {
      required: true,
      trigger: 'change',
      validator: (_, value) => {
        if (value.length === 0) return new Error('至少添加1门课程');
        // 检查是否有课程缺少必要信息
        const invalidCourse = value.find(c => !c.courseId || !c.credits);
        if (invalidCourse) return new Error('课程信息不完整（缺少ID或学分）');
        return true;
      }
    }
  ]
});

function submitForm() {
  proxy.$refs["trainingManagementRef"].validate(valid => {
    if (valid) {
      if (!form.value.courses || form.value.courses.length === 0) {
        proxy.$modal.msgWarning("请至少添加一门课程到培养方案中");
        return;
      }

      proxy.$modal.loading("正在提交培养方案及课程...");
      const programData = { ...form.value };
      if (form.value.collegeCode) {
        const college = collegeList.value.find(c => c.collegeCode === form.value.collegeCode);
        if (college) {
          programData.collegeId = college.collegeId;
        } else {
          proxy.$modal.closeLoading();
          proxy.$modal.msgError("未找到对应的学院信息，请重新选择学院");
          return;
        }
      }
      delete programData.courses;
      delete programData.courseSearch;
      delete programData.collegeCode;

      const coursesData = form.value.courses.map(course => ({
        id: course.id || null,
        courseId: course.courseId,
        courseCharacter: course.courseNature !== undefined ? parseInt(course.courseNature) : null,
        credits: course.credits != null ? Number(course.credits) : null,
        totalHours: course.totalHours != null ? Number(course.totalHours) : null,
        teachingMethod: course.teachingMethod ? parseInt(course.teachingMethod) : null,
        examMethod: course.examMethod ? parseInt(course.examMethod) : null,
        isRequired: course.isRequired ? parseInt(course.isRequired) : 0,
        grade: form.value.grade ? parseInt(form.value.grade) : null,
        semester: course.courseSemester ? parseInt(course.courseSemester) : null
      })).filter(course => course.courseId);

      if (coursesData.length === 0) {
        proxy.$modal.closeLoading();
        proxy.$modal.msgError("提交失败：所有添加的课程条目都缺少必要的课程ID信息。");
        return;
      }

      const payload = { program: programData, courses: coursesData };
      if (form.value.id == null) {
        addTrainingProgramWithCourses(payload)
            .then(response => {
              proxy.$modal.closeLoading();
              proxy.$modal.msgSuccess("新增培养方案及课程成功");
              open.value = false;
              getList();
              activeTab.value = 'program';
            })
            .catch(error => handleSubmitError(error, "新增"));
      } else {
        payload.program.id = form.value.id;
        updateProgramWithCourses(payload)
            .then(response => {
              proxy.$modal.closeLoading();
              proxy.$modal.msgSuccess("更新培养方案及课程成功");
              open.value = false;
              getList();
              activeTab.value = 'program';
            })
            .catch(error => handleSubmitError(error, "更新"));
      }
    } else {
      proxy.$modal.msgWarning("表单校验未通过，请检查培养方案必填项");
    }
  });
}

// 在现有计算属性下方添加
const isAuthorizedToReview = computed(() => {
  // 获取用户角色列表，默认空数组
  const userRoles = userStore.roles || [];
  // 检查是否包含 GraduateOffice 或 admin 角色
  return userRoles.includes('GraduateOffice') || userRoles.includes('admin');
});

function handleSubmitError(error, actionType) {
  proxy.$modal.closeLoading();
  console.error(`${actionType}失败:`, error);
  const errorMsg = error?.response?.data?.msg || error?.message || '操作失败，请检查数据或联系管理员';
  proxy.$modal.msgError(`${actionType}失败: ${errorMsg}`);
}

function reset() {
  form.value = {
    id: null,
    programCode: null,
    name: null,
    studentType: null,
    collegeId: null,
    collegeCode: null, // 补充初始值
    totalCredits: null,
    majorId: null,
    englishName: null,
    degreeCourseCredit: null,
    requiredCourseCredits: null,
    grade: null,
    cultureProgramType: null,
    majorCultureCategory: null,
    majorCode: null,
    majorName: null,
    attachmentUploadPath: null,
    limitingCondition: null,
    status: null,
    courses: [],
    courseSearch: '',
  };
  searchCourseList.value = [];
  proxy.resetForm("trainingManagementRef");
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  selectedRows.value = selection; // 保存选中的行数据
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加培养方案管理";
  activeTab.value = 'program';
}

function handleAddByPage() {
  router.push({
    path: '/trainingManagement-information',
    query: toRaw(queryParams.value)
  });
}

function navigateToDesignatedProgram(row) {
  router.push({
    path: '/designated-program',
    query: {
      id: row.id,
      amount: row.amount,
      customTime: row.customTime,
      electiveCourseCredits: row.electiveCourseCredits,
      practiceCredits: row.practiceCredits,
      studentType: row.studentType,
      programCode: row.programCode,
      name: row.name,
      collegeId: row.collegeId,
      totalCredits: row.totalCredits,
      majorId: row.majorId,
      englishName: row.englishName,
      degreeCourseCredit: row.degreeCourseCredit,
      requiredCourseCredits: row.requiredCourseCredits,
      grade: row.grade,
      cultureProgramType: row.cultureProgramType,
      status: row.status,
      attachmentUploadPath: row.attachmentUploadPath,
      limitingCondition: row.limitingCondition,
    }
  });
}
function handleAddFromTemplate() {
  // 只允许选择一个模板
  if (selectedRows.value.length !== 1) {
    proxy.$modal.msgWarning("请选择一个培养方案作为模板");
    return;
  }

  const template = selectedRows.value[0];
  router.push({
    path: '/trainingManagement-information',
    query: {
      ...toRaw(queryParams.value),
      fromTemplateId: template.id // 添加模板标识字段
    }
  });
}

function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  console.log(`开始加载培养方案详情，ID：${_id}`);

  Promise.all([
    getTrainingManagement(_id),
    getProgramPoursesByTrainingId(_id)
  ]).then(([trainingManagementResponse, programCoursesResponse]) => {
    form.value = trainingManagementResponse.data;
    // 初始化可能缺失的字段
    if (!form.value.courses) form.value.courses = [];
    if (!form.value.courseSearch) form.value.courseSearch = '';
    if (!form.value.collegeCode) form.value.collegeCode = '';

    console.log("培养方案基本信息加载完成", {
      collegeId: form.value.collegeId,
      majorId: form.value.majorId,
      name: form.value.name
    });

    if (form.value.collegeId) {
      // 根据学院ID查找学院信息
      const college = collegeList.value.find(c => c.collegeId === form.value.collegeId);
      if (college) {
        form.value.collegeCode = college.collegeCode;
        console.log(`匹配到学院代码：${college.collegeCode}（学院名称：${college.collegeName}）`);

        // 加载当前学院的专业列表
        getMajorByCollegeId(college.collegeCode).then(async (response) => {
          // 统一专业ID为字符串类型
          MajorList.value = (response.rows || response).map(major => ({
            ...major,
            id: major.id.toString()
          }));
          console.log(`加载到${MajorList.value.length}个属于该学院的专业`);

          // 处理专业回显
          if (form.value.majorId) {
            // 统一转为字符串进行比较
            const strMajorId = form.value.majorId.toString();
            let majorExists = MajorList.value.some(m => m.id === strMajorId);
            console.log(`专业ID ${strMajorId} 在学院专业列表中是否存在：${majorExists}`);

            if (!majorExists) {
              // 尝试直接查询该专业详情（可能跨学院）
              try {
                const majorDetail = await getMajor(form.value.majorId);
                if (majorDetail.data) {
                  // 将专业手动添加到列表，确保下拉选项存在
                  const formattedMajor = {
                    ...majorDetail.data,
                    id: majorDetail.data.id.toString() // 保持ID为字符串类型
                  };
                  MajorList.value.push(formattedMajor);
                  majorExists = true;
                  console.log("已补充加载跨学院专业详情：", formattedMajor.majorName);
                }
              } catch (error) {
                console.error(`专业ID ${form.value.majorId} 不存在：`, error);
              }
            }

            if (!majorExists) {
              proxy.$modal.msgWarning("当前专业不存在或不属于所选学院，已重置");
              form.value.majorId = null;
            } else {
              // 确保表单中的专业ID为字符串类型
              form.value.majorId = form.value.majorId.toString();
            }
          }
        });
      } else {
        console.warn(`未找到ID为${form.value.collegeId}的学院信息`);
      }
    }

    // 再次检查专业是否存在（防止学院加载失败的情况）
    if (form.value.majorId) {
      const strMajorId = form.value.majorId.toString();
      let majorExists = MajorList.value.some(m => m.id === strMajorId);
      console.log(`二次检查：专业ID ${strMajorId} 是否存在：${majorExists}`);

      if (!majorExists) {
        // 封装为async函数处理异步查询
        (async () => {
          try {
            const majorDetail = await getMajor(form.value.majorId);
            if (majorDetail.data) {
              // 将专业手动添加到列表，确保下拉选项存在
              const formattedMajor = {
                ...majorDetail.data,
                id: majorDetail.data.id.toString() // 保持ID为字符串类型
              };
              MajorList.value.push(formattedMajor);
              majorExists = true;
              form.value.majorId = formattedMajor.id; // 同步ID为字符串类型
              console.log("已补充加载专业详情：", formattedMajor.majorName);
            }
          } catch (error) {
            console.error(`专业ID ${form.value.majorId} 不存在：`, error);
            proxy.$modal.msgError("专业信息不存在，已重置");
            form.value.majorId = null;
          }
        })();
      }
    }

    // 处理课程数据
    if (programCoursesResponse && programCoursesResponse.data && Array.isArray(programCoursesResponse.data.rows)) {
      const linkedCourses = programCoursesResponse.data.rows;
      form.value.courses = linkedCourses.map(linkedCourse => {
        const fullCourseInfo = courseList.value.find(c => c.id === linkedCourse.courseId);
        if (!fullCourseInfo) {
          console.warn(`未找到ID为${linkedCourse.courseId}的课程`);
          return {
            courseId: linkedCourse.courseId,
            courseName: '未知课程',
            collegeId: null,
            courseCode: 'N/A',
            courseNature: linkedCourse.courseCharacter !== undefined ? String(linkedCourse.courseCharacter) : null,
            credits: linkedCourse.credits,
            totalHours: linkedCourse.totalHours,
            courseSemester: linkedCourse.semester,
            teachingMethod: linkedCourse.teachingMethod !== undefined ? String(linkedCourse.teachingMethod) : null,
            examMethod: linkedCourse.examMethod !== undefined ? String(linkedCourse.examMethod) : null,
            isRequired: linkedCourse.isRequired !== undefined ? (String(linkedCourse.isRequired) === '1' ? '1' : '0') : '0',
          };
        }
        return {
          courseId: linkedCourse.courseId,
          credits: linkedCourse.credits,
          totalHours: linkedCourse.totalHours,
          courseNature: linkedCourse.courseCharacter !== undefined ? String(linkedCourse.courseCharacter) : (fullCourseInfo.courseNature !== undefined ? String(fullCourseInfo.courseNature) : null),
          teachingMethod: linkedCourse.teachingMethod !== undefined ? String(linkedCourse.teachingMethod) : (fullCourseInfo.teachingMethod !== undefined ? String(fullCourseInfo.teachingMethod) : null),
          examMethod: linkedCourse.examMethod !== undefined ? String(linkedCourse.examMethod) : (fullCourseInfo.examMethod !== undefined ? String(fullCourseInfo.examMethod) : null),
          isRequired: linkedCourse.isRequired !== undefined ? (String(linkedCourse.isRequired) === '1' ? '1' : '0') : '0',
          courseSemester: linkedCourse.semester || fullCourseInfo.semester,
          courseStatus: linkedCourse.courseStatus !== undefined ? String(linkedCourse.courseStatus) : (fullCourseInfo.courseStatus !== undefined ? String(fullCourseInfo.courseStatus) : null),
          courseName: fullCourseInfo.courseName,
          collegeId: fullCourseInfo.collegeId,
          courseCode: fullCourseInfo.courseCode,
        };
      });
      updateTotalCredits();
      console.log(`已加载${form.value.courses.length}门关联课程`);
    } else {
      form.value.courses = [];
      console.log('未获取到关联课程或课程数据格式不正确:', programCoursesResponse);
    }

    open.value = true;
    title.value = "修改培养方案管理";
    activeTab.value = 'program';
  }).catch(error => {
    console.error('修改操作中加载数据失败:', error);
    proxy.$modal.msgError('加载培养方案信息或课程信息失败');
    if (form.value && !Array.isArray(form.value.courses)) {
      form.value.courses = [];
    }
  });
}

async function handleTrainingProgramWithCourses(row) {
  showTrainingProgramDialog.value = true;
  trainingProgramForm.programCode = row.programCode || '';
  trainingProgramForm.name = row.name || '';
  trainingProgramForm.collegeId = row.collegeId || '';
  trainingProgramForm.totalCredits = row.totalCredits || '';
  trainingProgramForm.majorId = row.majorId || '';
  trainingProgramForm.englishName = row.englishName || '';
  trainingProgramForm.degreeCourseCredit = row.degreeCourseCredit || '';
  trainingProgramForm.requiredCourseCredits = row.requiredCourseCredits || '';
  trainingProgramForm.grade = row.grade || '';
  trainingProgramForm.cultureProgramType = row.cultureProgramType || ''; // 修正拼写
  trainingProgramForm.id = row.id;

  try {
    const majorDetails = await getMajor(trainingProgramForm.majorId);
    majorForm.majorName = majorDetails.data.majorName;
    majorForm.majorCode = majorDetails.data.majorCode;
    majorForm.majorCultureCategory = majorDetails.data.cultureCategory;

    const studentRes = await listByStudentZyAndNj(majorForm.majorCode, trainingProgramForm.grade);
    if (studentRes.code === 200 && studentRes.rows) {
      studentMangerList.value = studentRes.rows;
    } else {
      console.error("获取学生列表失败:", studentRes.msg);
      proxy.$modal.msgError("获取学生列表失败");
    }
  } catch (error) {
    console.error("操作失败:", error);
    proxy.$modal.msgError("获取数据失败");
  }

  trainingProgramForm.status = row.status || '';
  trainingProgramForm.attachmentUploadPath = row.attachmentUploadPath || '';
  trainingProgramForm.limitingCondition = row.limitingCondition || '';
}

function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除培养方案管理编号为"' + _ids + '"的数据项？').then(function () {
    return delTrainingManagement(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

function handleExport() {
  proxy.download('trainingManagement/trainingManagement/export', {
    ...queryParams.value
  }, `trainingManagement_${new Date().getTime()}.xlsx`);
}

const programPoursesList = ref([]);
const spanData = ref([]);

function calculateSpanData() {
  const map = new Map();
  spanData.value = programPoursesList.value.map((item, index) => {
    const key = item.courseCharacter;
    if (!map.has(key)) {
      map.set(key, { index, count: 1 });
      return { rowspan: 1, colspan: 1 };
    } else {
      map.get(key).count++;
      return { rowspan: 0, colspan: 0 };
    }
  });
  map.forEach(({ index, count }) => {
    spanData.value[index].rowspan = count;
  });
}

function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  if (columnIndex === 0) {
    return spanData.value[rowIndex] || { rowspan: 1, colspan: 1 };
  }
  return { rowspan: 1, colspan: 1 };
}

function getProgramPoursesList() {
  listProgramPourses(loadAllParams).then(response => {
    programPoursesList.value = response.rows;
  });
}

async function getTrainingManagementCourseList(id) {
  if (!id) {
    proxy.$modal.msgError('培养方案 ID 为空，无法获取课程');
    return;
  }

  try {
    const res = await getProgramPoursesByTrainingId(id);
    const rows = res?.data?.rows || res?.data || [];
    if (!Array.isArray(rows) || rows.length === 0) {
      proxy.$modal.msgWarning('该培养方案暂无课程数据');
      programPoursesList.value = [];
      spanData.value = [];
      currentTrainingProgramName.value = getTrainingProgramName(id);
      openDetail.value = true;
      return;
    }

    const sorted = [...rows].sort((a, b) =>
        String(a.courseCharacter ?? '').localeCompare(String(b.courseCharacter ?? ''))
    );

    programPoursesList.value = sorted.map(item => ({
      ...item,
      courseName: getCourseName(item.courseId),
      courseCode: getCourseCode(item.courseId)
    }));

    calculateSpanData();
    currentTrainingProgramName.value = getTrainingProgramName(id);
    openDetail.value = true;
  } catch (e) {
    console.error('接口调用出错:', e);
    if (axios.isAxiosError(e)) {
      if (e.response) {
        console.error('服务器响应错误:', e.response.data);
        proxy.$modal.msgError(`获取课程信息失败，服务器响应错误: ${e.response.status} ${e.response.statusText}`);
      } else if (e.request) {
        console.error('没有收到服务器响应:', e.request);
        proxy.$modal.msgError('获取课程信息失败，没有收到服务器响应');
      } else {
        console.error('请求设置出错:', e.message);
        proxy.$modal.msgError(`获取课程信息失败，请求设置出错: ${e.message}`);
      }
    } else {
      proxy.$modal.msgError(`获取课程信息失败，发生未知错误: ${e.message}`);
    }
  }
}

function handleViewDetail(row) {
  getTrainingManagementCourseList(row.training_program_id);
  openDetail.value = true;
}

function getCourseList() {
  listCourse(loadAllParams).then(response => {
    courseList.value = response.rows;
  });
}

const MajorList = ref([]);
const getMajorList = () => {
  listMajor(loadAllParams).then(response => {
    // 将专业ID转为字符串，确保与回显的ID类型一致
    MajorList.value = (response.rows || []).map(major => ({
      ...major,
      id: major.id.toString() // 转为字符串
    }));
  });
};

const getMajorInfo = (majorId) => {
  if (!majorId) return '-';
  const major = MajorList.value.find(m => String(m.id) === String(majorId));
  if (major) {
    return `${major.majorName} (${major.majorCode})`;
  }
  return '未知专业';
};

function handleUpdates(row) {
  router.push({
    path: '/trainingManagement-information',
    query: {
      ...toRaw(queryParams.value),
      id: row.id
    }
  });
}

function handleCollegeChange(collegeCode) {
  console.log(`开始处理学院切换，学院代码：${collegeCode}`);
  const college = collegeList.value.find(c => c.collegeCode === collegeCode);

  if (college) {
    form.value.collegeId = college.collegeId;
    console.log(`匹配到学院：${college.collegeName}，ID：${college.collegeId}`);
  } else {
    form.value.collegeId = null;
    MajorList.value = [];
    form.value.majorId = null;
    console.log("未匹配到学院，重置学院ID和专业列表");
    return;
  }

  if (!collegeCode) return;

  // 保存当前专业ID并统一转为字符串类型，用于后续匹配
  const currentMajorId = form.value.majorId?.toString();
  console.log(`当前专业ID（字符串化）：${currentMajorId}`);

  getMajorByCollegeId(collegeCode).then(response => {
    // 将专业ID转为字符串，确保与表单值类型一致
    MajorList.value = (response.rows || response).map(major => ({
      ...major,
      id: major.id.toString()  // 强制转为字符串，解决类型不匹配问题
    }));
    console.log(`学院${collegeCode}加载到${MajorList.value.length}个专业`);

    // 若原专业属于新学院，则保留；否则重置
    if (currentMajorId) {
      const majorExists = MajorList.value.some(m => m.id === currentMajorId);
      console.log(`原专业在新学院列表中是否存在：${majorExists}`);

      if (!majorExists) {
        proxy.$modal.msgWarning("切换学院后，原专业已重置（不属于新学院）");
        form.value.majorId = null;
      }
    }
  }).catch(error => {
    console.error("查询专业失败：", error);
    proxy.$modal.msgError("获取专业列表失败");
  });
}

const allTrainingPrograms = ref([]);
async function getAllTrainingPrograms() {
  try {
    const response = await selectTrainingProgramListByCollegeIds({
      pageNum: 1,
      pageSize: 1000
    });
    allTrainingPrograms.value = response.rows;
  } catch (error) {
    console.error('获取培养方案失败:', error);
    proxy.$modal.msgError('培养方案加载失败');
  }
}

const isStudentSelectable = (row) => {
  const canSelect = !row.trainingProgramId;
  console.log(`学生 ${row.studentId} 是否可被选择：${canSelect}（已有方案：${row.trainingProgramId ? '是' : '否'}）`);
  return canSelect;
};

function getCourseName(courseId) {
  const course = courseList.value.find(c => c.id === courseId);
  return course ? course.courseName : '未知课程';
}

function getCourseCode(courseId) {
  const course = courseList.value.find(c => c.id === courseId);
  return course ? course.courseCode : '未知课程编号';
}

async function getCourseByTrainingId(trainingId) {
  try {
    const response = await getProgramPoursesByTrainingId(trainingId);
    if (response.data && Array.isArray(response.data.rows)) {
      return response.data.rows.map(course => ({
        ...course,
        courseName: getCourseName(course.courseId),
        courseCode: getCourseCode(course.courseId),
      }));
    }
    return [];
  } catch (error) {
    console.error('获取课程信息失败:', error);
    return [];
  }
}

const fetchCollegeList = async () => {
  collegeLoading.value = true;
  try {
    const res = await listCollege({ pageSize: 1000 });
    collegeList.value = res.rows;
    filteredColleges.value = res.rows;
  } catch (e) {
    console.error('学院列表加载失败', e);
    proxy.$modal.msgError('学院列表加载失败');
  } finally {
    collegeLoading.value = false;
  }
};

const filterColleges = debounce((query) => {
  collegeLoading.value = true;
  if (query) {
    const q = query.toLowerCase();
    filteredColleges.value = collegeList.value.filter(c =>
        c.collegeName.toLowerCase().includes(q) ||
        c.collegeCode.includes(query)
    );
  } else {
    filteredColleges.value = collegeList.value;
  }
  collegeLoading.value = false;
}, 300);

function handleStudentSelectionChange(selection) {
  selectedStudents.value = selection;
}

function closeTrainingDialog() {
  selectedStudents.value = [];
  assigning.value = false;
}

async function assignTrainingProgram() {
  if (selectedStudents.value.length === 0) {
    proxy.$modal.msgWarning("请至少选择一名学生");
    return;
  }
  assigning.value = true;
  try {
    const requestData = {
      trainingProgramId: trainingProgramForm.id,
      studentIds: selectedStudents.value.map(s => s.id)
    };
    const response = await assignTrainingToStudents(requestData);
    if (response.code === 200) {
      proxy.$modal.msgSuccess(response.msg);
      showTrainingProgramDialog.value = false;
      selectedStudents.value = [];
    } else {
      proxy.$modal.msgError(response.msg || "分配失败，请稍后重试");
    }
  } catch (error) {
    console.error("分配培养方案出错:", error);
    proxy.$modal.msgError("分配过程中发生错误");
  } finally {
    assigning.value = false;
  }
}

const getCollegeName = (collegeId) => {
  if (!collegeId) return '-';
  const college = collegeList.value.find(c => c.collegeId === collegeId);
  return college ? `${college.collegeName} (${college.collegeCode})` : '未知学院';
};

const getTrainingProgramName = (id) => {
  const program = allTrainingPrograms.value.find(item => item.id === id);
  return program ? program.name : '未知方案';
};
</script>

<style>
.flex-center { display: flex; align-items: center; justify-content: center; }
.tab-buttons {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}
.tab-btn { min-width: 120px; }
.training-detail-dialog .el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, .08);
}
.training-detail-dialog .el-table__header th:last-child { border-right: none; }
:deep(.el-dialog__footer) {
  display: flex !important;
  justify-content: center !important;
  padding: var(--el-dialog-padding-primary) !important;
}
:deep(.training-detail-dialog .el-dialog__footer) {
  justify-content: center !important;
}
.training-detail-dialog .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; height: 6px;
}
.search-container {
  position: relative;
  width: 400px;
}
.result-preview {
  padding: 6px 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}
.result-list {
  width: 600px;
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0,0,0,.1);
}
.result-item { padding: 8px 12px; cursor: pointer; transition: background .3s; }
.result-item:hover { background: #f5f7fa; }
.highlight { color: #409eff; font-weight: 500; }
.course-list {
  margin-top: 16px;
  border-top: 1px dashed #e4e7ed;
  padding-top: 16px;
}
.course-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}
@media (max-width: 1200px) {
  .search-course-group {
    flex-direction: column;
    align-items: flex-start;
  }
}
.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 2000;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0,0,0,.1);
  max-height: 300px;
  overflow-y: auto;
}
.selected-courses {
  border-top: 1px dashed #e4e7ed;
  padding-top: 16px;
}
.empty-tips {
  padding: 12px;
  background: #f8f8f8;
  border-radius: 4px;
}
:deep(.el-dialog__body) {
  border: 6px solid #40a9ff;
  border-radius: 6px;
  padding: 12px;
}
h1 {
  color: #40a9ff;
  font-weight: 600;
}
:deep(.training-assign-dialog .el-table__body tr:nth-child(even) td) {
  background-color: #fafafa !important;
}
:deep(.training-assign-dialog .el-table__body tr:nth-child(odd) td) {
  background-color: #ffffff !important;
}
:deep(.training-assign-dialog .el-table__header-wrapper th) {
  background-color:  #69c0ff !important;
  color: #fff !important;
}
:deep(.selected-courses .el-table__header th) {
  background-color: #69c0ff !important;
  color: #fff !important;
}
:deep(.selected-courses .el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}
/* 修复表格列对齐和偏移问题 */
:deep(.el-table__header-wrapper th, .el-table__body-wrapper td) {
  white-space: nowrap;
  text-align: center !important;
}

/* 确保表格布局正确 */
:deep(.el-table) {
  table-layout: fixed;
  width: 100% !important;
}

/* 处理内容过长的情况 */
:deep(.el-table .cell) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
/* 确保学科列有足够高度显示两行内容 */
:deep(.el-table-column[label="学科"] .cell) {
  white-space: normal !important;
  line-height: 1.5;
  padding: 8px 0;
  min-height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
